package com.oxygen.pt.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.gson.Gson;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.oxygen.pt.mapper.PatientMapper;
import com.oxygen.pt.pojo.entity.Patient;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class QRCodeUtils {

    @Resource
    private PatientMapper patientMapper;
    /**
     * 将Patient患者对象胜场二维码图像，并返回
     * @param patient 患者对象
     * @return 返回的File对象
     */
    public File creatQRImage(long id) {
        // 将 Patient 对象转化为 JSON 字符串
        Patient patient = patientMapper.getById(id);
        Gson gson = new Gson();
        String jsonString = gson.toJson(patient);

        // 创建二维码生成器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        // 定义二维码的相关配置
        int size = 300;  // 二维码的宽高
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 设置容错率
        hints.put(EncodeHintType.MARGIN, 1);  // 设置边距
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            // 生成二维码矩阵
            BitMatrix bitMatrix = qrCodeWriter.encode(jsonString, BarcodeFormat.QR_CODE, size, size, hints);

            // 将二维码矩阵转换为 BufferedImage
            BufferedImage bufferedImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }

            // 输出二维码图像文件
            File qrCodeFile = new File(
                    "E:\\Project\\JavaProject\\oxygen-manage\\pt-service\\src\\main\\resources\\static\\QRImage"
                            +patient.getName() + UUID.randomUUID() + "patient_code.png");
            javax.imageio.ImageIO.write(bufferedImage, "PNG", qrCodeFile);

            // 返回文件
            return qrCodeFile;
        } catch (WriterException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从输入流解析二维码文本
     * @param inputStream PNG/JPG 等格式
     * @return 二维码中的字符串
     * @throws IOException 读取异常
     * @throws NotFoundException 未找到二维码
     */
    public  String decode(InputStream inputStream)
            throws IOException, NotFoundException {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            throw new IllegalArgumentException("无法读取图片");
        }

        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Result result = new MultiFormatReader().decode(bitmap);
        return result.getText();
    }

    /**
     * 从本地文件解析
     */
    public  String decode(File file) throws IOException, NotFoundException {
        try (InputStream in = new FileInputStream(file)) {
            return decode(in);
        }
    }



}
